/*************************************************************************
** Copyright(c) 2016-2021  xktesla
** All rights reserved.
** Name		: TimerCall.h
** Desc		: 一个基于消息循环的定时器
** Author	: xktesla@2021-1-16 09:04:50
*************************************************************************/

#ifndef _80EBEBFA_46EA_4EBF_A60E_BAE658F428A9
#define _80EBEBFA_46EA_4EBF_A60E_BAE658F428A9

#ifdef __X2LIB_WIN32__

#include "depends/incfile.h"

namespace x2lib
{
	struct TimerCall
	{
	public:
        template<class T> TimerCall(HWND hWnd, bool/*是否Freeze*/ (T::*mfnCallProc)(void*, uint32_t), T* pThis, void* pVoid, uint32_t uTimes = 8, uint32_t uWaitms = 400)
		{
			this->hWnd = hWnd;
			//this->mfnCallProc = reinterpret_cast<bool (TimerCall::*)(void*)>(f);
            memcpy(&this->mfnCallProc, &mfnCallProc, sizeof(void*));
			this->pThis = pThis;
			this->pVoid = pVoid;
			this->uTimes = uTimes;
			this->uWaitms = uWaitms;
			this->_uTimes = uTimes;
		}

		static bool Wakeup(TimerCall* pTimerCall, bool isReset = true)
		{
			if (isReset) { pTimerCall->Reset(); }
			return (0 != ::SetTimer(pTimerCall->hWnd, (UINT_PTR)pTimerCall, pTimerCall->uWaitms, TimerCall::__TimerProc));
		}

		static void Freeze(TimerCall* pTimerCall)
		{
			::KillTimer(pTimerCall->hWnd, (UINT_PTR)pTimerCall);
		}

		void Reset()
		{
			this->uTimes = this->_uTimes;
		}

		bool f(void*) { return true; }

	private:
		//TimerCall() {};

		static void CALLBACK __TimerProc(HWND hWnd, UINT, UINT_PTR nIDEvent, DWORD)
		{
			TimerCall* ptc = (TimerCall*)nIDEvent;
			--ptc->uTimes;
			bool isFreeze = (((TimerCall*)ptc->pThis)->*(ptc->mfnCallProc))(ptc->pVoid, ptc->uTimes);

			//LOG_PRINT_D("ptc->uTimes=%d, isFreeze=%d\n", ptc->uTimes, isFreeze);
			if (ptc->uTimes <= 0 || isFreeze)
			{
				TimerCall::Freeze(ptc);
			}
		}

	public:
		//typedef void(*PFN_TIMERCALLPROC)(void* pVoid);
		//void* mfnCallProc;
		bool (TimerCall::*mfnCallProc)(void*, uint32_t); // 增加“TimerCall::”仅仅是为了能编译通过
		void* pThis;
		void* pVoid;
		uint32_t uTimes;
		uint32_t uWaitms;

	private:
        HWND hWnd;
		uint32_t _uTimes;
	};

}

#endif

#endif
